package game.bejeweled
{
	import com.yzy.tool.Utils;
	
	import flash.geom.Point;
	
	import control.IRunCtrl;
	
	import models.BallModel;
	import models.BallPool;
	import models.ProfileModel;
	
	import starling.display.Image;
	import starling.textures.Texture;
	
	public class Ball extends Image implements IRunCtrl
	{
		private var texture:Texture;
		
		public function Ball(texture:Texture)
		{
			super(texture);
//			this.touchable=false;
			this.pivotX=this.width>>1;
			this.pivotY=this.height>>1;
		}
		
		public var rowNum:int=-1;
		public var column:int=-1;
		public var ballProfile:BallModel;
		public var sign:int;
	    
		
		//*******************************
		//
		//*******************************
		public var ballSpeed:Number=20;
		
		private var friction:Number=0.9; 
		 
		private var _TargetP:Point;

		public function get TargetP():Point
		{
			return _TargetP;
		}

		public function set TargetP(value:Point):void
		{
			_TargetP = value;
			dx=_TargetP.x-this.x;
			dy=_TargetP.y-this.y;
			var dist:Number=Math.sqrt(dx*dx+dy*dy);
			var angle:Number=Math.atan2(dy,dx);
			vx=Math.cos(angle)*ballSpeed;
			vy=Math.sin(angle)*ballSpeed;
			//
			step=int(dist/ballSpeed);
		}
		private var dx:Number;
		private var dy:Number;
		private var step:int;
		private var vx:Number;
		private var vy:Number;
		private var spring:Number=0.2;
		private var minDist:Number=5;
		public var isSpring:Boolean=false;
			
		public function Run(CurrNum:int):void{
			if(!isSpring){
				step--
				if(step<=0){
					isSpring=true;
					var newAngle:Number=Utils.getRandom(0,2*Math.PI);
					vx=Math.cos(newAngle)*10;
					vy=Math.sin(newAngle)*10;
				}
			}
		    if(isSpring){
				this.alpha-=0.1;
				if(this.alpha<=0){
					BallPool.instant.returnClass(this);
					ProfileModel.instant._runVec.splice(CurrNum,1);
				}
			}
			this.x+=vx*friction;
			this.y+=vy*friction;
		}

		//********************************
		//
		//********************************
		public function reset():void{
			rowNum=-1;
			column=-1;
			this.alpha=1;
			this.scaleX=1;
			this.scaleY=1;
			isSpring=false;
			this.touchable=true;
			this.parent.removeChild(this,true);
		
		}
	}
}